{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "2ef21da3",
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "os.environ['CUDA_VISIBLE_DEVICES'] = ''\n",
    "os.environ['TF_FORCE_GPU_ALLOW_GROWTH'] = 'true'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "cd7155d5",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/home/ubuntu/.local/lib/python3.10/site-packages/bitsandbytes/cextension.py:34: UserWarning: The installed version of bitsandbytes was compiled without GPU support. 8-bit optimizers, 8-bit multiplication, and GPU quantization are unavailable.\n",
      "  warn(\"The installed version of bitsandbytes was compiled without GPU support. \"\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "/home/ubuntu/.local/lib/python3.10/site-packages/bitsandbytes/libbitsandbytes_cpu.so: undefined symbol: cadam32bit_grad_fp32\n",
      "[2023-08-21 03:27:30,479] [INFO] [real_accelerator.py:133:get_accelerator] Setting ds_accelerator to cuda (auto detect)\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "2023-08-21 03:27:30.839051: I tensorflow/core/platform/cpu_feature_guard.cc:182] This TensorFlow binary is optimized to use available CPU instructions in performance-critical operations.\n",
      "To enable the following instructions: AVX2 FMA, in other operations, rebuild TensorFlow with the appropriate compiler flags.\n",
      "2023-08-21 03:27:31.500075: W tensorflow/compiler/tf2tensorrt/utils/py_utils.cc:38] TF-TRT Warning: Could not find TensorRT\n"
     ]
    }
   ],
   "source": [
    "from transformers import LlamaConfig, LlamaForCausalLM"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "0616deb9",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "LlamaConfig {\n",
       "  \"_name_or_path\": \"meta-llama/Llama-2-7b-hf\",\n",
       "  \"architectures\": [\n",
       "    \"LlamaForCausalLM\"\n",
       "  ],\n",
       "  \"bos_token_id\": 1,\n",
       "  \"eos_token_id\": 2,\n",
       "  \"hidden_act\": \"silu\",\n",
       "  \"hidden_size\": 4096,\n",
       "  \"initializer_range\": 0.02,\n",
       "  \"intermediate_size\": 11008,\n",
       "  \"max_position_embeddings\": 4096,\n",
       "  \"model_type\": \"llama\",\n",
       "  \"num_attention_heads\": 32,\n",
       "  \"num_hidden_layers\": 16,\n",
       "  \"num_key_value_heads\": 32,\n",
       "  \"pad_token_id\": 0,\n",
       "  \"pretraining_tp\": 1,\n",
       "  \"rms_norm_eps\": 1e-05,\n",
       "  \"rope_scaling\": null,\n",
       "  \"tie_word_embeddings\": false,\n",
       "  \"torch_dtype\": \"float16\",\n",
       "  \"transformers_version\": \"4.31.0\",\n",
       "  \"use_cache\": true,\n",
       "  \"vocab_size\": 32000\n",
       "}"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "half_config = LlamaConfig.from_pretrained('meta-llama/Llama-2-7b-hf', \n",
    "                                             num_hidden_layers = 16)\n",
    "half_config"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "9067e90e",
   "metadata": {},
   "outputs": [],
   "source": [
    "half = LlamaForCausalLM(half_config)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "db3d7cf5",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "LlamaForCausalLM(\n",
       "  (model): LlamaModel(\n",
       "    (embed_tokens): Embedding(32000, 4096, padding_idx=0)\n",
       "    (layers): ModuleList(\n",
       "      (0-15): 16 x LlamaDecoderLayer(\n",
       "        (self_attn): LlamaAttention(\n",
       "          (q_proj): Linear(in_features=4096, out_features=4096, bias=False)\n",
       "          (k_proj): Linear(in_features=4096, out_features=4096, bias=False)\n",
       "          (v_proj): Linear(in_features=4096, out_features=4096, bias=False)\n",
       "          (o_proj): Linear(in_features=4096, out_features=4096, bias=False)\n",
       "          (rotary_emb): LlamaRotaryEmbedding()\n",
       "        )\n",
       "        (mlp): LlamaMLP(\n",
       "          (gate_proj): Linear(in_features=4096, out_features=11008, bias=False)\n",
       "          (up_proj): Linear(in_features=4096, out_features=11008, bias=False)\n",
       "          (down_proj): Linear(in_features=11008, out_features=4096, bias=False)\n",
       "          (act_fn): SiLUActivation()\n",
       "        )\n",
       "        (input_layernorm): LlamaRMSNorm()\n",
       "        (post_attention_layernorm): LlamaRMSNorm()\n",
       "      )\n",
       "    )\n",
       "    (norm): LlamaRMSNorm()\n",
       "  )\n",
       "  (lm_head): Linear(in_features=4096, out_features=32000, bias=False)\n",
       ")"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "half"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "4a67c76e",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "56c307963cc744f9a2f0b5ef3d1ae8ac",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Loading checkpoint shards:   0%|          | 0/2 [00:00<?, ?it/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "model = LlamaForCausalLM.from_pretrained('meta-llama/Llama-2-7b-hf')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "faa968a7",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "LlamaForCausalLM(\n",
       "  (model): LlamaModel(\n",
       "    (embed_tokens): Embedding(32000, 4096, padding_idx=0)\n",
       "    (layers): ModuleList(\n",
       "      (0-31): 32 x LlamaDecoderLayer(\n",
       "        (self_attn): LlamaAttention(\n",
       "          (q_proj): Linear(in_features=4096, out_features=4096, bias=False)\n",
       "          (k_proj): Linear(in_features=4096, out_features=4096, bias=False)\n",
       "          (v_proj): Linear(in_features=4096, out_features=4096, bias=False)\n",
       "          (o_proj): Linear(in_features=4096, out_features=4096, bias=False)\n",
       "          (rotary_emb): LlamaRotaryEmbedding()\n",
       "        )\n",
       "        (mlp): LlamaMLP(\n",
       "          (gate_proj): Linear(in_features=4096, out_features=11008, bias=False)\n",
       "          (up_proj): Linear(in_features=4096, out_features=11008, bias=False)\n",
       "          (down_proj): Linear(in_features=11008, out_features=4096, bias=False)\n",
       "          (act_fn): SiLUActivation()\n",
       "        )\n",
       "        (input_layernorm): LlamaRMSNorm()\n",
       "        (post_attention_layernorm): LlamaRMSNorm()\n",
       "      )\n",
       "    )\n",
       "    (norm): LlamaRMSNorm()\n",
       "  )\n",
       "  (lm_head): Linear(in_features=4096, out_features=32000, bias=False)\n",
       ")"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "model"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "32b16164",
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "LlamaDecoderLayer(\n",
       "  (self_attn): LlamaAttention(\n",
       "    (q_proj): Linear(in_features=4096, out_features=4096, bias=False)\n",
       "    (k_proj): Linear(in_features=4096, out_features=4096, bias=False)\n",
       "    (v_proj): Linear(in_features=4096, out_features=4096, bias=False)\n",
       "    (o_proj): Linear(in_features=4096, out_features=4096, bias=False)\n",
       "    (rotary_emb): LlamaRotaryEmbedding()\n",
       "  )\n",
       "  (mlp): LlamaMLP(\n",
       "    (gate_proj): Linear(in_features=4096, out_features=11008, bias=False)\n",
       "    (up_proj): Linear(in_features=4096, out_features=11008, bias=False)\n",
       "    (down_proj): Linear(in_features=11008, out_features=4096, bias=False)\n",
       "    (act_fn): SiLUActivation()\n",
       "  )\n",
       "  (input_layernorm): LlamaRMSNorm()\n",
       "  (post_attention_layernorm): LlamaRMSNorm()\n",
       ")"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "model.model.layers[0]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "a6413f42",
   "metadata": {},
   "outputs": [],
   "source": [
    "import torch.nn as nn\n",
    "\n",
    "def copy_layers(src_layers, dest_layers, layers_to_copy):\n",
    "    layers_to_copy = nn.ModuleList([src_layers[i] for i in layers_to_copy])\n",
    "    assert len(dest_layers) == len(layers_to_copy), f\"{len(dest_layers)} != {len(layers_to_copy)}\"\n",
    "    dest_layers.load_state_dict(layers_to_copy.state_dict())\n",
    "\n",
    "layers_to_copy = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]\n",
    "\n",
    "copy_layers(model.model.layers, half.model.layers, layers_to_copy)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "id": "68baf555",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Linear(in_features=4096, out_features=32000, bias=False)"
      ]
     },
     "execution_count": 22,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "half.lm_head"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "90ea1a2e",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<All keys matched successfully>"
      ]
     },
     "execution_count": 16,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "half.model.embed_tokens.load_state_dict(model.model.embed_tokens.state_dict())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "id": "5f4fbf73",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<All keys matched successfully>"
      ]
     },
     "execution_count": 19,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "half.model.norm.load_state_dict(model.model.norm.state_dict())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "id": "d999dfa8",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<All keys matched successfully>"
      ]
     },
     "execution_count": 25,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "half.lm_head.load_state_dict(model.lm_head.state_dict())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "03fbd7ca",
   "metadata": {},
   "outputs": [],
   "source": [
    "half.save_pretrained(\"7b-half\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "bc57cc85",
   "metadata": {},
   "outputs": [],
   "source": [
    "!ls -lh 7b-half"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
